<template>
  <div id="addSpacePage">
    <h2 style="margin-bottom: 16px; text-align: center">创建{{ SPACE_TYPE_MAP[spaceType] }}</h2>
    <!-- 空间信息表单 -->
    <a-form layout="vertical" :model="spaceForm" @finish="handleSubmit">
      <a-form-item label="云空间名称" name="name">
        <a-input
          v-model:value="spaceForm.spaceName"
          placeholder="给云空间起个好听的名字吧"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="云空间级别">
        <a-select
          v-model:value="spaceForm.spaceLevel"
          placeholder="请选择云空间级别，未选择默认创建最高等级"
          :options="SPACE_LEVEL_DETAIL_OPTIONS"
          allow-clear
          style="min-width: 150px"
          @change="handleSelectChange"
        />
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          :loading="loading"
          block
          :icon="h(CloudOutlined)"
        >
          创建云空间
        </a-button>
      </a-form-item>
    </a-form>
    <a-card title="云空间级别介绍">
      <a-typography-paragraph>
        支持创建 普通版 会员版 超级会员版 三种个人云空间
      </a-typography-paragraph>
      <a-typography-paragraph v-if="spaceLevelList[0]">
        {{ spaceLevelList[0].text }}：最大容量 {{
          formatSizeNoDecimalFraction(spaceLevelList[0].maxSize)
        }}
        ，可上传{{ spaceLevelList[0].maxCount }}张图片
      </a-typography-paragraph>
      <a-typography-paragraph v-if="spaceLevelList[1]">
        {{ spaceLevelList[1].text }}：最大容量 {{
          formatSizeNoDecimalFraction(spaceLevelList[1].maxSize)
        }}
        ，可上传{{ spaceLevelList[1].maxCount }}张图片
        <!-- 开通会员 气泡确认框 -->
        <a-popconfirm
          title="确认开通会员吗?"
          ok-text="确认"
          cancel-text="取消"
          @cancel="upgradeUserRoleToVip"
        >
          <template #icon>
            <question-circle-outlined style="color: #1677ff" />
          </template>
          <a href="#">
            <a-button
              v-if="loginUser.userRole === 'user'"
              :icon="h(SketchOutlined)"
              type="link"
              :style="{ color: '#E4080A', opacity: 0.9 }"
            >
              开通会员
            </a-button>
          </a>
        </a-popconfirm>
      </a-typography-paragraph>
      <a-typography-paragraph v-if="spaceLevelList[2]">
        {{ spaceLevelList[2].text }}：最大容量 {{
          formatSizeNoDecimalFraction(spaceLevelList[2].maxSize)
        }}
        ，可上传{{ spaceLevelList[2].maxCount }}张图片
        <!-- 开通超级会员 气泡确认框 -->
        <a-popconfirm
          title="确认开通超级会员吗?"
          ok-text="确认"
          cancel-text="取消"
          @cancel="upgradeUserRoleToSvip"
        >
          <template #icon>
            <question-circle-outlined style="color: #1677ff" />
          </template>
          <a href="#">
            <a-button
              v-if="loginUser.userRole === 'user' || loginUser.userRole === 'vip'"
              :icon="h(CrownOutlined)"
              type="link"
              :style="{ color: '#9400D3', opacity: 0.9 }"
            >
              开通超级会员
            </a-button>
          </a>
        </a-popconfirm>
      </a-typography-paragraph>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, h, onMounted, reactive, ref } from 'vue'
import { addSpaceUsingPost, listSpaceLevelUsingGet } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import {
  CloudOutlined,
  SketchOutlined,
  CrownOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons-vue'
import { SPACE_LEVEL_DETAIL_OPTIONS, SPACE_TYPE_ENUM, SPACE_TYPE_MAP } from '@/constants/space.ts'
import { formatSizeNoDecimalFraction } from '../utils'
import { useLoginUserStore } from '@/stores/useLoginUserStores.ts'

const router = useRouter()
const route = useRoute()

const space = ref<API.SpaceVO>()
// 空间信息表单，类型是创建空间请求体，默认是空对象
const spaceForm = reactive<API.SpaceAddRequest>({})

// 空间级别列表
const spaceLevelList = ref<API.SpaceLevel[]>([])

// 空间类型，默认为私有空间
const spaceType = computed(() => {
  if (route.query?.type) {
    return Number(route.query.type)
  } else {
    return SPACE_TYPE_ENUM.PRIVATE
  }
})

const loginUserStore = useLoginUserStore()
const loginUser = loginUserStore.loginUser

const loading = ref(false)

// 选择空间级别后简洁展示
const handleSelectChange = (value: number) => {
  if (value === 0 || value === 1 || value === 2) {
    const selectedOption = SPACE_LEVEL_DETAIL_OPTIONS.find((option) => option.value === value)
    if (selectedOption) {
      // 提取简洁信息
      // @ts-ignore
      spaceForm.spaceLevel = selectedOption.label.split('【')[0]
    }
  } else if (value === null) {
    // @ts-ignore
    spaceForm.spaceLevel = null
  }
}

/**
 * 提交表单创建空间
 * @param values
 */
const handleSubmit = async (values: any) => {
  loading.value = true
  // @ts-ignore
  if (spaceForm.spaceLevel === '普通版') {
    spaceForm.spaceLevel = 0
    // @ts-ignore
  } else if (spaceForm.spaceLevel === '会员版') {
    spaceForm.spaceLevel = 1
  } else {
    spaceForm.spaceLevel = 2
  }
  const res = await addSpaceUsingPost({
    ...spaceForm,
    spaceType: spaceType.value,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('创建成功')
    // 跳转到空间详情页
    router.push({
      path: `/space/${res.data.data}`,
    })
  } else {
    if (spaceForm.spaceLevel === 0) {
      // @ts-ignore
      spaceForm.spaceLevel = '普通版'
    } else if (spaceForm.spaceLevel === 1) {
      // @ts-ignore
      spaceForm.spaceLevel = '会员版'
    } else {
      // @ts-ignore
      spaceForm.spaceLevel = '超级会员版'
    }
    message.error('创建失败，' + res.data.message)
  }
  loading.value = false
}

/**
 * 远程获取空间级别详情列表
 */
const fetchSpaceLevelList = async () => {
  const res = await listSpaceLevelUsingGet()
  if (res.data.code === 0 && res.data.data) {
    spaceLevelList.value = res.data.data
  } else {
    message.error('获取空间级别详情列表失败，' + res.data.message)
  }
}

onMounted(() => {
  fetchSpaceLevelList()
})
</script>

<style scoped>
#addSpacePage {
  max-width: 550px;
  margin: 0 auto;
}
</style>
